<?php

/**
 * 角色services
 * @author wangwx 2015-4-14
 */

namespace common\services\myhtsq;

use Yii;
use common\services\BaseService;
use common\repositories\myhtsq\ErpUserRepository;
use common\repositories\myhtsq\RoleUserRepository;
use common\repositories\myhtsq\RoleRepository;
use common\repositories\myhtsq\RoleActionPackageRepository;
use common\repositories\myhtsq\ActionPackageRelationRepository;


class RoleService extends BaseService {
    /**
     * 获取角色功能授权缓存key
     * @param integer $id 用户ID
     * @return string
     */
    public static function getRoleAuthorizationKey($id){
        return 'role_auth_actions_cache_key_'.$id;
    }
    /**
     * 检查用户动作点权限
     * @param integer $userId 用户ID
     * @param string $actionCode 动作点编号
     * @return boolean 是否有权限
     */
    public static function checkAccess($userId, $actionCode) {
        $actions = self::getAuthCache($userId);
        //管理员用户不校验权限
        if ($actions === true) {
            return true;
        }else if($actions === false){
        	return false;
        }else{
        	return in_array($actionCode, $actions, true);
        }
    }
    
    /**
     * 检查用户动作点权限
     * @param integer $userId 用户ID
     * @param string $actionCode 动作点编号
     * @return boolean 是否有权限
     */
    public static function checkLoginUserAccess($actionCode) {
        if (Yii::$app->user->isGuest) {
            return false;
        }
        return static::checkAccess(Yii::$app->user->identity->userguid, $actionCode);
    }
    
    /**
     * 检查用户动作点权限
     * @param integer $userId 用户ID
     * @return boolean|a 是否有权限
     */
    public static function getAuthCache($userId) {
        $key = self::getRoleAuthorizationKey($userId);
        $actions = Yii::$app->cache->get($key);
        if (is_null($actions) || $actions === false) {
            self::setAuthCache($userId);
        }
        $actions = Yii::$app->cache->get($key);
        return $actions;
    }
    
    

    /**
     * 加载用户授权缓存数据
     * @param integer $userId 用户ID
     */
    private static function setAuthCache($userId) {
        $key = self::getRoleAuthorizationKey($userId);
        //如果当前用户是管理员，返回true
        /*$user = ErpUserRepository::getUserById($userId);
        if ($user->IsAdmin) {
            Yii::$app->cache->set($key, true, 36000);
            return;
        }*/

        //获取用户所属角色
        $actions = [];
        $roleUserResp = new RoleUserRepository();
        $roleResp = new RoleRepository();
        $rolePackageResp = new RoleActionPackageRepository();
        $rolesList = $roleUserResp->getRolesByUserId($userId);
        
        // 特殊处理：如果用户不属于合同查看权限外的任一个角色，则默认赋予合同查看权限
        /*if (empty($rolesList)) {
            array_push($rolesList, (object)['role_id'=>'1']);
        }*/
        
        if (!empty($rolesList)) {
            foreach ($rolesList as $idx => $role) {
                $roleTmp = $roleResp->getRoleByRoleId($role->role_id);
                if (is_null($roleTmp)) {
                    continue; //角色无效
                }

                //获取角色对应的功能包
                $roleActionPackages = $rolePackageResp->getAllRoleActionPackageByRoleId($role->role_id);
                if (count($roleActionPackages) === 0) {
                    continue;
                }
                //获取功能包对应的动作点
                /**
                 * @var $package \common\entities\myhtsq\RoleActionPackageEntity
                 */
                foreach ($roleActionPackages as $idx => $package) {
                    $actionsTmp = ActionPackageRelationRepository::getActionsByPackageId($package->action_package_id);
                    if (count($actionsTmp) === 0) {
                        continue;
                    }
                    /**
                     * @var $action \common\entities\myhtsq\ActionEntity
                     */
                    foreach ($actionsTmp as $idxA => $action) {
                        array_push($actions, $action->action_code);
                    }
                }
            }
        }

        Yii::$app->cache->set($key, $actions, 36000);
    }
    
    /**
     * 检查是否唯一的角色
     * @param string $userId 用户ID
     * @param string $roleId 角色ID
     * @return boolean
     */
    public static function checkOnlyOneRole($userId, $roleId) {
        $roleIds = RoleUserRepository::getRoleIdsByUserId($userId);
        if(count($roleIds) == 1 && in_array($roleId, $roleIds)) {
            return true;
        }
    }

}
